import React from 'react'
import { connect } from 'dva'
import { withRouter } from 'react-router-dom'

import Bar from '../Bar'
import './style.css'

const BuyBar = ({ history, commodity, dispatch, cart }) => {
    const goHome = () => {
        history.push('/')
    }
    const goCart = () => {
        history.push('/cart')
    }
    const createOrder = () => {
        // 1. 把当前商品添加到购物车
        // 2. 跳转
        dispatch({ 
            type: 'order/createrOrder', 
            payload: commodity 
        })
        history.push('/createOrder')
    }
    const pushCart = () => {
        let data = { ...commodity }
        if (cart.cart.map[commodity._id]) {
            data = {
                ...data,
                ...cart.cart.map[commodity._id]
            }
            data.count++
        }
        dispatch({
            type: 'cart/pushCart',
            payload: data
        })
    }
    
    let left = (
        <div className='buyBar-service'>
            <div onClick={goHome}>
                <i className='iconfont icon-home'></i>
                <span>店铺</span>
            </div>
            <div onClick={goCart} className='buyBar-service_cart' >
                <i className='iconfont icon-gouwuche-01'></i>
                <span>购物袋</span>
                {
                    cart.total.count !== 0 && (
                        <b>{cart.total.count}</b>
                    )
                }
            </div>
        </div>
    )
    let right = (
        <div 
            className='buyBar-addCard'
        >
            <span 
                style={{ fontSize: 14 }}
                onClick={pushCart}
            >
                加入购物车
            </span>
        </div>
    )
    return (
        <Bar
            className='buyBar'
            left={left}
            right={right}
            clickBuy={createOrder}
        />
    )
}

const mapState = state => ({
    cart: state.cart
})

export default connect(mapState)(withRouter(BuyBar))
